package cn.wolfcode.web.controller;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @RequestMapping("/list")
    @RequiredPermission(name="角色列表",expression = "permission:list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Role> pageResult = roleService.query(qo);
        model.addAttribute("pageInfo", pageResult);
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions",permissions);
        return "role/list";
    }
    @RequiredPermission(name="角色删除",expression = "permission:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        if(id !=null){
            roleService.delete(id);
        }
        return new JsonResult();
    }

    @RequiredPermission(name="角色录入",expression = "permission:input")
    @RequestMapping("/input")
    public String input(Long id, Model model){
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions",permissions);
        if (id !=null){
            Role role = roleService.get(id);
            model.addAttribute("role",role);
        }
        return "role/input";
    }
    @RequiredPermission(name="角色编辑或者保存",expression = "permission:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){
        if(role.getId() !=null){
            roleService.update(role,ids);
        }else{
            roleService.save(role,ids);
        }
        return "redirect:/role/list.do";
    }
}
